#include <stdlib.h>
#include <stdio.h>
#include<ctype.h> 
#include<unistd.h>
#include<stdlib.h>
#include<netdb.h>
#include <string.h>
#include <memory>
#include "session.h"
#include <iostream>
#include "../chat/chatmessagetask.h"
#include "../app/mainapp.h"

namespace QinChat{
    namespace Net{
        CSession::CSession(const struct sockaddr_in& client_addr, int fd):m_clientfd(fd){
            memcpy(&m_clientAddr, &client_addr, sizeof(struct sockaddr_in));
        }

        CSession::~CSession(){
            std::cout<<"close socket socket_id is:" <<  m_clientfd;
            close(m_clientfd);
        }

        int CSession::GetFd(void) const{
            return m_clientfd;
        }

        void CSession::Recv(char* pszMessage, int len){
            std::cout<<"create messate task"<<std::endl;
            std::shared_ptr<Core::CTask> ptrTask = std::make_shared<Chat::CChatMessageTask>(shared_from_this(), pszMessage, len);
            std::cout<<"push messate task"<<std::endl;
            App::CMainApp::GetInstace().GetThreadPool().PushTask(ptrTask);
        }

        void CSession::Send(char* pszMessage, int len){
            ssize_t wd = ::write(m_clientfd,(const void *)pszMessage, len + 1);
            if (wd > 0) {
                std::cout<<"client fd is : " << m_clientfd<<" success to send messega is : "<<pszMessage<<std::endl;
            } else if (wd == -1 && errno == EINTR) {
                std::cout<<"client fd is : " << m_clientfd<<" success to send messega is : "<<pszMessage<<std::endl;
            } else if (wd == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
//                break;
            }
            std::cout<<"client fd is : " << m_clientfd<<" messega is : "<<pszMessage<<std::endl;
        }
    }
}